package com.hymall.service.wx;

import com.hymall.bean.MarketStorage;
import com.hymall.mapper.MarketStorageMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Date;
import java.util.UUID;

/**
 * @author: 牟治宇
 * @description 图片上传实体类
 * @date: 2022/7/19 11:11
 */
@Service
public class WxStorageServiceImpl implements WxStorageService {

    @Autowired
    MarketStorageMapper marketStorageMapper;


    @Override
    public MarketStorage uploadPic(MultipartFile file) throws FileNotFoundException {

        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        String originalFilename = file.getOriginalFilename();

        String extensionName = originalFilename.substring(originalFilename.lastIndexOf("."));

        uuid = uuid + extensionName;
        String contentType = file.getContentType();

        String url = "http://localhost:8083" +"/image/" + uuid;
        // String temp = pathPattern.substring(0, pathPattern.length() - 2);
        String filePath = "D:\\hymall\\image";

        // File path = new File(ResourceUtils.getURL("file:").getPath());
        File dest = new File(filePath + "/" + uuid);


        try {
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            if (!dest.exists()) {
                dest.createNewFile();
            }
            // String absolutePath = file.getAbsolutePath();
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }

        long size = file.getSize();

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(uuid);
        marketStorage.setSize(size);
        marketStorage.setAddTime(new Date(System.currentTimeMillis()));
        marketStorage.setName(originalFilename);
        marketStorage.setDeleted(true);
        marketStorage.setType(contentType);
        marketStorage.setUpdateTime(marketStorage.getAddTime());
        marketStorage.setUrl(url);

        int code = marketStorageMapper.insert(marketStorage);

        return marketStorage;
    }
}
